package controllers

import (
	"errors"
	"fmt"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"

	"github.com/myblogs/logic"
	"github.com/myblogs/models"
)

type ArticleHandleImpl struct {
	artLogic logic.ArticleInterface
}

func NewArticleHandleImpl(artLogic logic.ArticleInterface) *ArticleHandleImpl {
	return &ArticleHandleImpl{
		artLogic: artLogic,
	}
}
func (a *ArticleHandleImpl) CreateArticlaHandler(c *gin.Context) {
	var req models.ReqArtical
	if err := c.ShouldBindJSON(&req); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if ok {
			zap.S().Error("创建文章参数错误", zap.Error(err))
			ResponseWithMsg(c, CodeInvalidParam, removeTopStruct(errs.Translate(trans)))
			return
		}
		Response(c, CodeInvalidParam)
		return
	}

	article, err := a.artLogic.CreatedArtical(c.Request.Context(), &req)
	if err != nil {
		if errors.Is(err, logic.ErrorTagExits) {
			zap.S().Error("用户id获取失败", zap.Error(err))
			Response(c, CodeUserIdExits)
			return
		}
		zap.S().Error("创建文章失败", zap.Error(err))
		Response(c, CodeArticleExits)
		return
	}
	ResponseSuccess(c, CodeSuccess, map[string]interface{}{
		"article_id": article.ArticleID,
	})
}
func (a *ArticleHandleImpl) GetArticleByIDHandler(c *gin.Context) {
	articleID, err := strconv.ParseInt(c.Param("id"), 10, 64)
	fmt.Println(articleID, "98600566657024")
	if err != nil {
		zap.S().Error("获取文章ID失败", zap.Error(err))
		Response(c, CodeInvalidParam)
		return
	}
	article, err := a.artLogic.GetArticleByID(c.Request.Context(), articleID)
	if err != nil {
		zap.S().Error("获取文章失败", zap.Error(err))
		Response(c, CodeArticleNotExits)
		return
	}
	ResponseSuccess(c, CodeSuccess, article)
}
func (a *ArticleHandleImpl) GetAllArticlesHandler(c *gin.Context) {
	articles, err := a.artLogic.GetAllArticles(c.Request.Context())
	if err != nil {
		zap.S().Error("获取文章失败", zap.Error(err))
		Response(c, CodeArticleNotExits)
		return
	}
	ResponseSuccess(c, CodeSuccess, articles)
}
func (a *ArticleHandleImpl) GetArticleByUserIDHandler(c *gin.Context) {
	articles, err := a.artLogic.GetArticleByUserID(c.Request.Context())
	if err != nil {
		if errors.Is(err, logic.ErrorUserIDExits) {
			zap.S().Error("获取用户ID失败", zap.Error(err))
			Response(c, CodeUserNotExits)
			return
		}
		zap.S().Error("获取文章失败", zap.Error(err))
		Response(c, CodeArticleNotExits)
		return
	}

	ResponseSuccess(c, CodeSuccess, map[string]interface{}{
		"articles": articles,
		"total":    len(*articles),
	})
}
